﻿using Chat.Common;
using log4net.Repository.Hierarchy;
using SuperSocket.SocketBase.Command;
using SuperSocket.SocketBase.Protocol;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ChatServerLib
{
    /// <summary>
    /// 加入聊天
    /// </summary>
    public class JOIN : CommandBase<ChatSession, StringRequestInfo>
    {

        public override void ExecuteCommand(ChatSession session, StringRequestInfo requestInfo)
        {
            string body = requestInfo.Body;
            try
            {
                body = Base64.Decode(body);
            }
            catch { }
            session.Logger.DebugFormat("Got command: {0}=>{1}", requestInfo.Key, body);

            string username = body;

            ResultStatus rs = new ResultStatus(ResultType.JOIN_RESULT);

            // 用户未输入昵称
            if (string.IsNullOrWhiteSpace(username))
            {
                rs.Success = false;
                rs.Message = "Please enter your Nickname.";
                session.Send(rs.ToString());
                return;
            }


            var sessions = session.AppServer.GetSessions(_ => !string.IsNullOrWhiteSpace(_.UserName)).ToList();

            // 昵称已经存在
            if (sessions.Any(_ => _.UserName.Equals(username, StringComparison.OrdinalIgnoreCase)))
            {
                rs.Success = false;
                rs.Message = "Nickname [" + username + "] exists, please get another one.";
                session.Send(rs.ToString());
                return;
            }


            // 昵称不存在，可以加入聊天
            session.UserName = username;
             
            rs.Message = "Yoo.. [" + username + "], welcome. You can chat now.";
            rs.Data = string.Join(",", sessions.Select(_ => _.UserName).ToArray());

            session.Send(rs.ToString());

            // 通知其它用户
            ResultStatus rst = new ResultStatus(ResultType.NEW_JOIN);
            var targetSessions = session.AppServer.GetSessions(_ => !string.IsNullOrWhiteSpace(_.UserName) && _.SessionID != session.SessionID);

            rst.Message = string.Format("[{0}] joined.", username);
            rst.Data = username;
            string msg = rst.ToString();
            foreach (var item in targetSessions)
            {
                item.Send(msg);
            }
        }
    }
}
